<template>
    <div class="app-container">
      <nabars index="3"></nabars>
      <topIndex style="margin-bottom: 20px;" :indexCount="indexCount"></topIndex>
      <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
        <div class="from-item">
          <el-form-item label="群名称" prop="wcGroupName">
            <el-input v-model="queryParams.wcGroupName" @keyup.enter.native="handleQuery" placeholder="请输入群名称" clearable/>
          </el-form-item>
          <el-form-item label="助手名称" prop="nickName">
            <el-input v-model="queryParams.nickName" @keyup.enter.native="handleQuery" placeholder="请输入助手名称" clearable/>
          </el-form-item>
          <el-form-item label="在群助手" prop="wcName" v-if="!common">
            <!-- <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入在群助手" clearable/> -->
            <el-select style="width: 120px;" v-if="!qommon"
              v-model="queryParams.deptId"
              @change="getDept"
              placeholder="请选择区域"
              clearable
            >
              <el-option
                v-for="dict in deptName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-autocomplete style="width: 160px;"
              class="my-autocomplete"
              v-model="param.lable"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
            ></el-autocomplete>
            <!-- <el-select
              v-model="queryParams.wcId"
              placeholder="请选择助手"
              clearable
            >
              <el-option
                v-for="dict in userName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item label="聊天时间" prop="chatTime">
            <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </div>
        <div class="from-Btn">
          <el-form-item>
            <el-button class="blue-button" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </div>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleUpdate()"
          >批量绑定</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="wcGroupsInfoList" :header-cell-style="{ background: '#fcfcfd', color: '#000' }" :border="false" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="群名称" prop="wcGroupName" align="center" :show-overflow-tooltip="true"/>

        <el-table-column label="最近聊天时间" prop="lastChatTime" align="center" :show-overflow-tooltip="true" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastChatTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
        </el-table-column>
        <el-table-column label="地区/部门" prop="deptName" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="在群助手" prop="nickName" align="center" :show-overflow-tooltip="true"/>
        <el-table-column label="群好友占比" prop="groupFirendsNum" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope" v-if="scope.row.groupFirendsNum!=null">
            <span>{{scope.row.groupFirendsNum}}人</span>
          </template>
        </el-table-column>
        <el-table-column label="群标签" prop="labelName" align="center" :show-overflow-tooltip="true"/>
        <el-table-column align="center" width="120" class-name="small-padding fixed-width">
          <template slot="header">
            <span>AI功能</span>
            <el-tooltip class="item" effect="dark" content="进入操作" placement="top">
              <i class="el-icon-warning" style="color:#818e96;"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.openAi" @change="getEide(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" width="120" class-name="small-padding fixed-width">
          <template slot="header">
            <span>绑定标签</span>
            <el-tooltip class="item" effect="dark" content="点击操作" placement="top">
              <i class="el-icon-warning" style="color:#818e96;"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
           <span style="color:#0078fb;cursor: pointer;" @click="handleUpdate(scope.row)">绑定</span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" width="120" class-name="small-padding fixed-width">
          <template slot="header">
            <span>群操作</span>
            <el-tooltip class="item" effect="dark" content="进入操作" placement="top">
              <i class="el-icon-warning" style="color:#818e96;"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
           <span style="color:#0078fb;cursor: pointer;margin-right: 10px;" @click="handleUpdate(scope.row)">绑定标签</span>
           <span style="color:#0078fb;cursor: pointer;" @click="golink(scope.row.wcGroupId,scope.row.wcId,scope.row.wcName)">详情</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog title="绑定标签" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="绑定标签" prop="dictLabel">
              <el-select v-model="form.labelId" placeholder="请选择标签" clearable>
                <el-option v-for="dict,index in lableInfo" :key="index" :label="dict.dictLabel"
                  :value="dict.dictCode" />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
      </el-dialog>
    </div>
  </template>

  <script>

  import request from '@/utils/request'
  import nabars from '../components/nabar.vue'
  import mathNum from "../components/daily.js"
  import topIndex from '../components/top-index.vue'
  import { checkPermi } from "@/utils/permission";
  import { listDept } from "@/api/system/dept";
  import { listWcUser } from "@/api/system/user";
  export default {
    name: "WcGroupsInfo",
    dicts: ['sys_friend_proport'],
    components:{
        nabars,
      topIndex,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 微信群信息表格数据
        wcGroupsInfoList: [],
        // 是否显示弹出层
        open: false,
        chatTime:[],
        param:{
          wcId: null,
          lable:null,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wcId: null,
          deptId: null,
          assistId: null,
          wcName:null,
          wcGroupName: null,
          nickName: null,
          wcGroupNoteName: null,
          beginTime: null,
          endTime: null,
          begin:null,
          end:null,
        },
        form:{labelId:null,dataId:null,type:'group_label'},
        common:false,
        qommon:false,
        indexCount:[{name:'今日新加群',num:0,type:1,bili:0},{name:'今日新加群内好友',num:0,type:1,bili:0},{name:'今日群内发言',num:0,type:1,bili:0}],
        lableInfo:[],
          userParams: {
          pageNum: 1,
          pageSize: 9999,
          deptId: undefined,
        },
        deptName:[],
        userName:[],
        };
    },
    created() {
      if (this.$store.state.user.roles.includes("common")) {
        this.common = true;
        this.qommon=true;
      }
      if (this.$store.state.user.roles.includes("qxleader")) {
        this.common = false;
        this.qommon=true;
      }
      if(!this.qommon){
        var deptName=[]
        listDept().then(response => {
          if(response.code==200){
            response.data.forEach((item) =>{
              deptName.push({value:item.deptId,label:item.deptName})
            })
            this.deptName=deptName
          }
        });
      }else{
        var userName=[]
        this.userParams=null
        listWcAssist(this.userParams).then((res) => {
          if (res["success"]) {
            const dt = res["data"];
            dt["records"].forEach((element) => {
              //userName.push({value:element.wcId,label:element.wcName})
              userName.push({value:element.wcName,label:element.wcId})
            });
          }
          this.userName=userName
        });
      }
    },
    mounted() {
      this.groupLabel()
      this.getList();
      this.init()
    },
    methods: {
      checkPermi,
      init(){
        getNewGroupNum().then(res => {
          //console.log(res)
          if(res.code==200){
            if(res.data){
                this.indexCount[0].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
                this.indexCount[0].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
                this.indexCount[0].num=res.data.new_size
            }
          }
        })
        getGroupsFriend().then(res => {
          //console.log(res)
          if(res.code==200){
            if(res.data){
                this.indexCount[1].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
                this.indexCount[1].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
                this.indexCount[1].num=res.data.new_size
            }
          }
        })
        getGroupSpeak().then(res => {
          //console.log(res)
          if(res.code==200){
            if(res.data){
                this.indexCount[2].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
                this.indexCount[2].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
                this.indexCount[2].num=res.data.new_size
            }
          }
        })
      },
      golink(groupid,wxid,name){
        if(this.checkPermi(['massage:massage:getMags'])){
          this.$router.push({ path:"/group/detial/",name:'detial',query: { groupid,wxid,name}}).catch(()=>{});
        }else{
          this.$router.push({ path:"/group/notadd/",name:'notadd',query: {wxid,groupid,name}}).catch(()=>{});
        }
      },
      /** 查询微信群信息列表 */
      getList() {
        this.loading = true;
        var param=this.queryParams
        if(this.param.wcId!=null){
          param.wcId=this.param.wcId
        }
        listWcGroupsInfo(param).then(res => {
          //console.log(res)
          if (res['success']) {
            const dt = res['data'];
            this.total = dt['map'].total;
            this.wcGroupsInfoList = dt['wcGrpupsinfoVsitList'];
          }
          this.loading = false;
        });
        setTimeout(()=>{
          this.loading = false;
        },2000)
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          wcId: null,
          assistId: null,
          wcGroupName: null,
          wcGroupId: null,
          wcGroupNoteName: null,
          wcGroupNum: null,
          groupFirendsNum: null,
          groupFirendsScale: null,
          lastChatTime: null,
          remark: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null
        };
        this.resetForm("form");
      },
      getEide(row){
        var openAi=row.openAi?1:0
        editOpenAi({id:row.id,openAi}).then(res => {
           this.$modal.msgSuccess("修改成功");
        });
      },
      groupLabel(){
        groupLabel().then(res => {
          //console.log(res)
          if(res.code==200){
            this.lableInfo=res.data
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.beginTime=null
        this.queryParams.endTime=null
        if(this.chatTime!=''&&this.chatTime!=null){
          this.queryParams.beginTime=this.chatTime[0]+' 00:00:00'
          this.queryParams.endTime=this.chatTime[1]+' 23:59:59'
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.chatTime=[]
        this.queryParams.wcId=null
        this.queryParams.deptId=null
        this.handleQuery();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        //console.log(row)
        this.form={labelId:null,dataId:null,type:'group_label'}
        this.open=true
        if(row) {
          this.form.dataId=row.id
        }
      },
      /** 提交按钮 */
      submitForm() {
        this.form.dataId = this.form.dataId || this.ids.join(',');
        this.$refs["form"].validate(valid => {
          if (valid) {
            groupBind(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.form.dataId = null;
              this.open = false;
              this.getList();
            });
          }
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        //console.log('ids = ',this.ids)
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      getDept(value) {
        if(value!=''){
          this.userParams.deptId=value
          this.queryParams.wcId=null
          var userName=[]
          listWcUser(this.userParams).then((res) => {
            //console.log(res)
              if (res["code"]==200) {
              const dt = res["rows"];
              dt.forEach((element) => {
                if(this.userParams.deptId==100){
                  if(element.deptId==100&&element.wcId!=''&&element.wcId!=null){
                    // userName.push({value:element.wcId,label:element.nickName})
                    userName.push({value:element.nickName,label:element.wcId})
                  }
                }else if(element.wcId!=''&&element.wcId!=null){
                  // userName.push({value:element.wcId,label:element.nickName})
                  userName.push({value:element.nickName,label:element.wcId})
                }
              });
            }
            this.userName=userName
          });
        }
      },
      querySearch(queryString, cb) {
        var restaurants = this.userName;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        this.param.lable=item.value
        this.param.wcId=item.label
      },
    }
  };

  /** js请求 调用 */

  // 查询微信群信息列表
  export function listWcGroupsInfo(query) {
    return request({
      url: '/arbit/wcgroups_info/page',
      method: 'get',
      params: query
    })
  }

  // 今日群好友统计
  export function getGroupsFriend(data) {
    return request({
      url: '/arbit/wcgroups_user/data_groups_friendln',
      method: 'get',
      data: data
    })
  }
  // 今日新加群
  export function getNewGroupNum(data) {
    return request({
      url: '/arbit/wcgroups_info/data_groups',
      method: 'get',
      data: data
    })
  }
  // 群内发言
  export function getGroupSpeak(data) {
    return request({
      url: '/arbit/wcgroups_info/dayGroupsSpeak',
      method: 'get',
      data: data
    })
  }
  //修改群AI状态
  export function editOpenAi(data) {
    return request({
      url: '/arbit/wcgroups_info/OpenAi',
      method: 'put',
      data: data
    })
  }
  //获取所有群库标签
  export function groupLabel() {
    return request({
      url: '/label/relevance/type/group_label',
      method: 'GET',
    })
  }
  //群库绑定标签
  export function groupBind(data) {
    return request({
      url: '/label/relevance/bind',
      method: 'post',
      data: data
    })
  }
  // 查询助手信息列表
  export function listWcAssist(query) {
    return request({
      url: "/arbit/wcuser_info/page",
      method: "get",
      params: query,
    });
  }
  </script>
  <style scoped lang="scss">
    .app-container{
      background-color: #f6f9fb;
    }
    .my-autocomplete {width: 160px;}
    .frominfo{
      display: flex;background-color: #fff;padding: 10px;padding-bottom: 0; margin-bottom: 20px;
      .from-item{
        display: flex;flex-wrap: wrap;
      }
      .from-Btn{
        display: flex;flex-direction: column;align-items: center;justify-content: center;width: 20%;
      }
    }
    .blue-button {
      color: #fff;
      background-color: #0078fb;
      border-color: #0078fb;
    }

  </style>
